package com.wanfajie.smsdistribute.main.fragment.group

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.app.AlertDialog
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.OrientationHelper
import android.support.v7.widget.RecyclerView
import android.view.*
import android.widget.EditText
import com.wanfajie.smsdistribute.R
import com.wanfajie.smsdistribute.db.bean.phone.PhoneGroup
import com.wanfajie.smsdistribute.db.repository.impl.GroupRepositoryImpl
import com.wanfajie.smsdistribute.util.toast

class PhoneGroupFragment : Fragment() {

    private lateinit var mContextView : View

    // XXX: 为解决屏幕旋转导致activity和context属性为null, 可能存在内存泄露的风险
    // 目前的情况是这个Fragment只会被Attach到MainActivity,
    // 且MainActivity存在于整个应用周期, 理论上问题不大
    private lateinit var mActivity: Activity
    private val mRecyclerView: RecyclerView by lazy {
        mContextView.findViewById<RecyclerView>(R.id.group_list).apply {

            layoutManager = LinearLayoutManager(mActivity).apply {
                orientation = OrientationHelper.VERTICAL
            }

            addItemDecoration(DividerItemDecoration(mActivity, OrientationHelper.VERTICAL))
        }
    }

    private lateinit var mAdapter: PhoneGroupRecyclerAdapter

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {

        if (!::mContextView.isInitialized) {
            mContextView = inflater.inflate(R.layout.fragment_group, container, false)

            mAdapter = PhoneGroupRecyclerAdapter(mActivity, emptyList())
            mRecyclerView.adapter = mAdapter
        }
        setHasOptionsMenu(true)

        return mContextView
    }

    private fun createNewGroup(groupName : String) {
        val group = PhoneGroup(groupName = groupName)
        if (GroupRepositoryImpl.hasName(groupName)) {
            toast("$groupName 已存在")
            return
        }

        if (GroupRepositoryImpl.saveGroup(group)) {
            mAdapter.addItem(0, group)
            toast("创建成功")
        } else {
            toast("创建失败")
        }
    }

    private fun showAlertForGroupName() {
        val view = View.inflate(mActivity, R.layout.alert_create_group, null)
        val etGroupName = view.findViewById<EditText>(R.id.et_group_name)

        AlertDialog.Builder(mActivity)
                .setTitle("新建分组")
                .setView(view)
                .setNegativeButton("取消", null)
                .setPositiveButton("创建") { _, _ ->

                    if (!etGroupName.text.isEmpty()) {
                        createNewGroup(etGroupName.text.toString())
                    } else {
                        toast("必须填写分组名")
                    }
                }
                .setCancelable(false)
                .create()
                .show()
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {

        return when (item?.itemId) {
            R.id.add -> {
                showAlertForGroupName()
                true
            }
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onAttach(context: Context?) {
        super.onAttach(context)
        mActivity = activity!!
    }

    override fun onStart() {
        super.onStart()

        mAdapter.setData(GroupRepositoryImpl.getGroups())
    }

    override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
        inflater?.inflate(R.menu.menu_frag_phone_group, menu)
    }
}
